<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="省市区县" prop="countyCode">
        <RegionPicker v-model="formData.countyCode" />
      </el-form-item>
      <el-form-item v-if="formData.countyCode" label="详细地址" prop="detailAddress">
        <el-input v-model="formData.detailAddress" placeholder="请输入详细地址" clearable />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="formData.longitude" placeholder="请输入经度" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="formData.latitude" placeholder="请输入纬度" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="">
        <el-button type="primary" @click="pickLocation" :loading="locationLoading"
          >获取经纬度</el-button
        >
      </el-form-item>
      <p class="mx-5 text-gray-400">
        此处的经纬度使用的是国测局坐标系（GCJ20），高德地图及腾讯地图默认已支持 GCJ20
        ，百度地图及谷歌地图则需要转换为 GCJ20 。<span class="text-red-300"
          >可使用地图坐标拾取工具复制经纬度坐标粘贴进上面的经纬度输入框中。</span
        ><br />
        高德地图坐标拾取工具：<a href="https://lbs.amap.com/tools/picker" target="_blank"
          >点击打开</a
        >
        。<br />
        腾讯地图坐标拾取工具：<a
          href="https://lbs.qq.com/tool/getpoint/get-point.html"
          target="_blank"
          >点击打开</a
        >
        。
      </p>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <LatLngPicker ref="locationPickerRef" v-model="location" />
  </el-drawer>
</template>
<script setup lang="ts">
import { AddressVO, ShopInfoApi } from '@/api/mall/shop/info'
import { getConfigKey } from '@/api/infra/config'
import { RegionPicker } from '@/views/universal/region'
import { LatLngPicker } from '@/components/Location'

/** 店铺经营地址 表单 */
defineOptions({ name: 'AddressForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  countyCode: undefined,
  detailAddress: undefined,
  latitude: undefined,
  longitude: undefined
})
const formRules = reactive({
  countyCode: [{ required: true, message: '省市区县不能为空', trigger: 'blur' }],
  detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ShopInfoApi.getShopInfo(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AddressVO
    await ShopInfoApi.updateAddress(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    countyCode: undefined,
    detailAddress: undefined,
    latitude: undefined,
    longitude: undefined
  }
  formRef.value?.resetFields()
}

const locationPickerRef = ref()
const locationLoading = ref(false)
const location = computed({
  get: () => {
    return {
      lat: formData.value.latitude,
      lng: formData.value.longitude
    }
  },
  set: (newValue: any) => {
    formData.value.latitude = newValue.lat
    formData.value.longitude = newValue.lng
  }
})
const pickLocation = () => {
  locationLoading.value = true
  getConfigKey('tencent.lbs.key')
    .then((res) => {
      console.log('获取腾讯地图 API 密钥：', res)
      // 打开地图选择经纬度
      locationPickerRef.value?.openMap(res)
    })
    .finally(() => {
      locationLoading.value = false
    })
}

/** 初始化 **/
onMounted(() => {})
</script>
<style lang="scss">
.mapBox .el-dialog__body {
  height: 640px !important;
}
</style>
